import {
    getBindCompanySupplier,
} from '../../../api/app.js'
import {
    addInsuranceEnterprise,
    addInsuranceEnterpriseGsc
} from '../../api/insurance'
import user from '../../../utils/user.js'
import {
    toast,
    dateFormat
} from '../../../utils/util'
import global from '../../../utils/global'
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        enterprise: [],
        // 投保时间弹框控制
        isInsuranceTime: false,
        dayInsureTime: '', // 白班投保时间
        nightInsureTime: '', // 夜班投保时间
        id: '',
        name: '',
        mediaList: [],
        params: {
            photos: [], // 图片视频
        },
        bankType: '',
        textareaInput: '',
        isSelect: false,
        isRadio: false,
        selects: [],
        isVideo: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log(options, user.insureCompanyType, 'options')
        if (options.form === 'list') {
            this.setData({
                isInsuranceTime: true,
                id: options.id,
                name: options.name,
            })
        }
        this.setData({
            isSelect: !!options.select,
            isRadio: options.radio,
        })
    },
    onShow: function () {
        user.waitLogin().then(() => {
            this.init()
            this.setData({
                isAdmin: user.isAdmin,
                bankType: user.insureCompanyType
            })
        })
    },
    init() {
        getBindCompanySupplier({
            companyId: user.companyId,
            searchOpenWesure: 1
        }).then(res => {
            this.setData({
                enterprise: res
            })
        })
    },
    onAdd() {
        this.setData({
            mediaList: [],
            textareaInput: ''
        })
        wx.navigateTo({
            url: '/pages/enterprise/enterprise?select=1&radio=1&searchOpenWesure=0',
            events: {
                complete: data => {
                    if (data.length) {
                        this.setData({
                            isInsuranceTime: true,
                            id: data[0].id,
                            name: data[0].name,
                        })
                        // const ids =data.map(item=>{
                        //     return item.id
                        // })

                    }
                }
            },
            success: (res) => {
                const data = this.data.enterprise.map(item => {
                    return item.id
                })
                res.eventChannel.emit('selects', data)
            }
        })
    },
    hidePopupForm() {
        this.setData({
            isInsuranceTime: false
        })
    },
    // 选择白班投保时间
    dayBindTimeChange(event) {
        const date = dateFormat('YY-mm-dd', new Date()) + ' ' + event.detail.value + ':00'
        const time = Date.create(date).getTime() + 1000 * 60 * 90
        const delayTime = dateFormat('HH:MM', new Date(time))
        this.setData({
            dayInsureTime: event.detail.value + '-' + delayTime
        }, () => {})
    },
    // 选择夜班投保时间
    nightBindTimeChange(event) {
        const date = dateFormat('YY-mm-dd', new Date()) + ' ' + event.detail.value + ':00'
        const time = Date.create(date).getTime() + 1000 * 60 * 90
        const delayTime = dateFormat('HH:MM', new Date(time))
        this.setData({
            nightInsureTime: event.detail.value + '-' + delayTime
        }, () => {})
    },
    // 提交投保时间
    onSubmitInsureTime() {
        if (this.data.dayInsureTime || this.data.nightInsureTime) {
            addInsuranceEnterprise({
                id: this.data.id,
                wesureTimeDayShiftAudit: this.data.dayInsureTime,
                wesureTimeNightShiftAudit: this.data.nightInsureTime,
                insureCompanyType: user.insureCompanyType
            }).then(() => {
                app.toast('添加成功', 'success')
                this.init()
                this.setData({
                    isInsuranceTime: false
                })
            })
        } else {
            toast('请至少选择一个投保时间')
        }
    },
    onGoEdit() {

    },
    onShowInsuranceTime(event) {
        const {
            type,
            day,
            id,
            name,
            night,
            all
        } = event.currentTarget.dataset
        // gsc 走这下面的 逻辑
        if (user.insureCompanyType === 'insure002_gsc') {
            if (Number(all)) {
                wx.navigateTo({
                    url: '/packageInsurance/pages/insurance-time/insurance-time?id=' + id + '&all=' + Number(all),
                })
                return
            }
            if (type === 3 || type === 2 || type === 1) {
                wx.navigateTo({
                    url: '/packageInsurance/pages/insurance-time/insurance-time?id=' + id,
                })
                return
            }
        }
        // 维保
        if (user.insureCompanyType === 'insure001_wesure') {
            if (Number(all)) {
                wx.navigateTo({
                    url: '/packageInsurance/pages/insurance-time/insurance-time?id=' + id + '&all=' + Number(all),
                })
                return
            }
            if (type === 1 || type === 0 || type === 2) {
                const data = {
                    day: day,
                    id: id,
                    name: name,
                    night: night
                }
                wx.navigateTo({
                    url: '/packageInsurance/pages/insurance-organize-edit/insurance-organize-edit?id=' + data.id,
                    success: function (res) {
                        // 通过eventChannel向被打开页面传送数据
                        res.eventChannel.emit('acceptDataFromOpenerPage', data)
                    }
                })
            } else if (type === 3) {
                wx.navigateTo({
                    url: '/packageInsurance/pages/insurance-time/insurance-time?id=' + event.currentTarget.dataset.id,
                })
            }
        }

    },
    // 上传视频
    upload() {
        wx.chooseMedia({
            count: 3,
            mediaType: ['image', 'video'],
            sourceType: ['album', 'camera'],
            // maxDuration: 30,
            sizeType: ['compressed'],
            success: (res) => {
                if (res.tempFiles[0].duration > 30) {
                    toast('请将视频时长控制在30秒以内')
                    return
                }
                if (res.tempFiles[0].fileType === 'video' && res.tempFiles[0].size > 30 * 1024 * 1024) {
                    toast('请将视频大小控制在30MB以内')
                    return
                }
                if (this.data.mediaList.length >= 3) {
                    toast('最多上传三个视频或图片')
                    return
                }
                const temporary = []
                temporary.push(...this.data.mediaList)
                temporary.push(...res.tempFiles)
                this.setData({
                    mediaList: temporary
                })
            }
        })
    },

    async onAddInsurance() {
        if (!this.data.textareaInput) {
            toast('请填写申请理由')
            return
        }
        this.data.mediaList.forEach(item => {
            if (item.fileType === 'video') {
                this.setData({
                    isVideo: true
                })
            }
        })
        if (!this.data.isVideo) {
            toast('请至少上传一个视频')
            return
        }
        if (this.data.mediaList.length >= 1) {
            this.filePush(this.data.mediaList)
        } else {
            this.insuranceEnterpriseGsc()
        }
        // this.setData({
        //     mediaList:[],
        //     textareaInput:''
        // })
    },

    // 文件批量上传并保存
    async filePush(tempFiles) {
        wx.showLoading({
            title: '文件上传中',
            mask: true
        })
        let promise = Promise.all(tempFiles.map((item) => {
            return new Promise((resolve) => {
                wx.uploadFile({
                    url: global.baseUrl + '/api/v1/pay/wesure-report-case/upload',
                    filePath: item.tempFilePath,
                    name: 'file',
                    success(res) {
                        resolve(res.data)
                    },
                    fail() {}
                })
            })
        }))
        promise.then(res => {
            const files = []
            res.forEach(item => {
                const url = JSON.parse(item).data.fileUrl
                const size = JSON.parse(item).data.fileSize
                let type = 'image'
                if (
                    /(mp4|flv|mov|wmv|avi|mpeg|rmvb)$/.test(url.toLowerCase())
                ) {
                    type = 'video'
                }
                files.push({
                    fileUrl: url,
                    fileType: type,
                    fileSize: size
                })
                this.setData({
                    ['params.photos']: files
                }, () => {})
                wx.hideLoading()
            })
            this.insuranceEnterpriseGsc()
        })
    },
    insuranceEnterpriseGsc() {
        addInsuranceEnterpriseGsc({
            serveCompanyId: this.data.id,
            params: this.data.params,
            remark: this.data.textareaInput,
            insureCompanyType: user.insureCompanyType,
            applySource: 0
        }).then(() => {
            this.init()
            toast('创建成功')
            this.setData({
                isInsuranceTime: false
            })
        })
    },
    // 视频，图片删除
    onDelete(event) {
        let {
            index
        } = event.currentTarget.dataset
        this.data.mediaList.splice(index, 1)
        this.setData({
            mediaList: this.data.mediaList
        })
    },

    // 点击图片放大
    onPreview(event) {
        const {
            url
        } = event.currentTarget.dataset
        wx.previewImage({
            urls: [url]
        })
    },
    onPlay(event) {
        // 获取 video 上下文 videoContext 对象
        this.videoContext = wx.createVideoContext(event.currentTarget.id, this)
        // 进入全屏状态
        this.videoContext.requestFullScreen()
        return 0
    },
    textareaInput(event) {
        this.setData({
            textareaInput: event.detail.value
        })
    },
    onSelect(event) {
        let selects = this.data.selects
        const data = event.currentTarget.dataset
        if (this.data.isRadio) { // 单选

            selects = [{
                name: data.name,
                id: data.id,
                position: data.position,
                phone: data.phone,
            }]
        } else {
            let index = -1
            for (const i in selects) {
                if (selects[i].id === data.id) {
                    index = i
                }
            }
            if (index === -1) {
                selects.push({
                    id: data.id,
                })
            } else {
                selects.splice(index, 1)
            }
        }

        this.setData({
            selects
        })
    },
    onSelectComplete() {
        // this.setData({
        //     isInsuranceTime:true
        // })
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.emit('complete', this.data.selects)
        wx.navigateBack()
    },
})